<?php
/**
 * crcl/base
 *
 * Copyright 2013 CRCL - André Sabosch - info@crcl.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace crcl\base\exception\printer;

interface IConcrete
{
  /**
   * Writes output and headers
   */
  public function write(\crcl\base\exception\IData $oData);
}

abstract class Base implements IConcrete
{
  const OUTPUT_STATUS = 'status';
  const OUTPUT_DEBUG  = 'debug';

  //@codeCoverageIgnoreStart
  abstract public function write(\crcl\base\exception\IData $oData);
  //@codeCoverageIgnoreEnd

  public function __construct($sTier)
  {
    if (isset($_SERVER['HTTP_ACCEPT']))
    {
      if ((\strpos($_SERVER['HTTP_ACCEPT'], 'api rest') !== \FALSE) &&
        (\strpos($_SERVER['HTTP_ACCEPT'], 'vnd.crcl') !== \FALSE))
      {
        $this->bRest = \TRUE;
      }
    }
  }

  /** PROTECTED ***********************************************************************************/

  protected function getOutput($sDirectory, \crcl\base\exception\IData $oData)
  {
    $sTemplate = \dirname(__FILE__) . \DIRECTORY_SEPARATOR .
      'templates' . \DIRECTORY_SEPARATOR .
      $sDirectory . \DIRECTORY_SEPARATOR .
      self::evaluateType() . '.php';

    \ob_start();
    include $sTemplate;
    $sOutput = \ob_get_clean();

    return $sOutput;
  }

  protected function isRest()
  {
    return $this->bRest;
  }

  /** PRIVATE *************************************************************************************/

  const TYPE_HTML = 'html';
  const TYPE_TXT  = 'txt';
  const TYPE_JSON = 'json';

  private $bRest = \FALSE;

  private function evaluateType()
  {
    $sType = self::TYPE_HTML;
    if (\crcl\base\Console::isCli())
    {
      $sType = self::TYPE_TXT;
    }
    if ($this->isRest())
    {
      $sType = self::TYPE_JSON;
    }
    return $sType;
  }
}